package com.lucy.nepu.module.paper.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.nepu.anno.WorkloadLimit;
import com.lucy.nepu.constant.ResearchTypeConst;
import com.lucy.nepu.loader.PeriodLoader;
import com.lucy.nepu.module.paper.entity.Paper;
import com.lucy.nepu.module.paper.lib.PaperDict;
import com.lucy.nepu.module.paper.lib.PaperDictService;
import com.lucy.nepu.module.paper.params.PaperCreateParams;
import com.lucy.nepu.module.paper.service.PaperService;
import com.lucy.nepu.module.paper.utils.PaperUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author kindear
 * 论文管理
 */
@RestController
@RequestMapping("nepu")
@Api(tags = "论文管理")
public class PaperController {
    @Autowired
    PaperService service;

    @Autowired
    PaperDictService dictService;

    @Autowired(required = false)
    PeriodLoader periodLoader;

    @WorkloadLimit(num = 3,type = ResearchTypeConst.PAPER) // 拦截周期内工作量不允许超出3个
    @PostMapping("papers")
    @ApiOperation(value = "论文新建",notes = "")
    public ResponseDTO<Object> paperCreate(@RequestBody @Validated PaperCreateParams params){
        // 1. 表单校验
        String errMsg = PaperUtil.formValid(params);
        if (!Validator.isEmpty(errMsg)){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,errMsg);
        }
        // 2. 获取当前时间所在周期ID
        String periodId = periodLoader.getPeriodId();
        // 3. 获取词典信息 -- 修改为计算形式
        PaperDict dict = dictService.getOneUnwrap(params.getPaperDictId());
        // 4. 写入记录 并赋值最大工作量
        Paper paper = new Paper();
        paper.setPeriodId(periodId);
        paper.setWorkload(dict.getWorkloadMax());
        BeanUtil.copyProperties(params,paper, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        return ResponseDTO.succData(
                service.saveOne(paper)
        );
    }

    @DeleteMapping("papers/{id}")
    @ApiOperation(value = "论文删除",notes = "")
    public ResponseDTO<Object> paperDelete(@PathVariable("id") String id){
        service.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }
}
